<template>
  <div style="margin-top:15px;">
    <div class="header">
      <h2 class="title">选择学院、年级、班级和学期</h2>
      <el-button type="primary" @click="fetchOrders" class="query-button">查询</el-button>
    </div>
    <el-form ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="学院">
            <el-select v-model="selectedCollege" placeholder="请选择学院" @change="onCollegeChange">
              <el-option v-for="college in colleges" :key="college.id" :label="college.name"
                :value="college.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="年级" :rules="[{ required: true, message: '请选择年级', trigger: 'change' }]">
            <el-select v-model="selectedGrade" placeholder="请选择年级">
              <el-option v-for="year in years" :key="year" :label="`${year}年入学`" :value="year"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="班级" :rules="[{ required: true, message: '请选择班级', trigger: 'change' }]">
            <el-select v-model="selectedClass" placeholder="请选择班级">
              <el-option v-for="classItem in classes" :key="classItem.id" :label="classItem.name" :value="classItem.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="学期" :rules="[{ required: true, message: '请选择学期', trigger: 'change' }]">
            <el-select v-model="selectedSemester" placeholder="请选择学期">
              <el-option v-for="semester in semesters" :key="semester.id" :label="semester.name"
                :value="semester.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 加载动画 -->
    <div v-if="loading" class="loading-overlay">
      <el-spin class="loading-spinner" size="large"></el-spin>
      <p class="loading-text">正在加载中</p>
    </div>
    <div v-if="tag === 0 && !loading" class="no-data-container">
      <h2 style="text-align: center;margin-top: 200px;color: #7c7c7c;">暂无数据</h2>
    </div>

    <!-- 表格展示 -->
    <div v-if="tag === 1 && !loading" class="table-container">
      <h2>订单统计</h2>
      <el-button type="success" @click="exportToExcel" class="export-button" >导出Excel</el-button>
      <table>
        <thead>
          <tr>
            <th>书名</th>
            <th>作者</th>
            <th>类别</th>
            <th>描述</th>
            <th>单价</th>
            <th>总数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="book in bookTableData" :key="book.name">
            <td>{{ book.name }}</td>
            <td>{{ book.author }}</td>
            <td>{{ book.category }}</td>
            <td>{{ book.description }}</td>
            <td>{{ book.unitPrice }}元</td>
            <td>{{ book.quantity }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { fetchColleges, fetchSemesters, fetchClasses } from "@/api/api";
//import * as XLSX from 'xlsx';

export default {
  name: "AdminOrderView",
  setup() {
    const colleges = ref([]);
    const classes = ref([]);
    const semesters = ref([]);
    const selectedCollege = ref(null);
    const selectedGrade = ref(null);
    const selectedSemester = ref(null);
    const selectedClass = ref(null);
    const years = ref(Array.from({ length: new Date().getFullYear() - 1900 }, (_, i) => new Date().getFullYear() - i));
    const bookTableData = ref([]);
    const loading = ref(false);  // 新增的 loading 状态
    const tag = ref(0);

    const fetchCollegesData = async () => {
      try {
        const data = await fetchColleges();
        colleges.value = data.map(college => ({
          id: college.id,
          name: college.name,
        }));
      } catch (error) {
        ElMessage.error(error.message);
      }
    };

    const fetchSemestersData = async () => {
      try {
        const data = await fetchSemesters();
        semesters.value = data;
      } catch (error) {
        ElMessage.error("网络错误或服务器无响应");
      }
    };

    const fetchClassesData = async () => {
      if (!selectedCollege.value || !selectedGrade.value) {
        ElMessage.warning("请选择学院和年级");
        classes.value = [];
        selectedClass.value = null;
        return;
      }
      try {
        const data = await fetchClasses(
          selectedGrade.value,
          selectedCollege.value
        );
        classes.value = data.map(classItem => ({
          id: classItem.id,
          name: classItem.name,
        }));
        sortClasses(); // 获取数据后立即排序
      } catch (error) {
        ElMessage.error(error.message);
        classes.value = [];
        classes.value = [];
      }
    };

    const onCollegeChange = () => {
      selectedClass.value = null;       // 清空班级选择
      selectedSemester.value = null;    // 清空学期选择
      fetchClassesData();               // 更新班级数据
    };

    const fetchOrders = async () => {
      if (!selectedGrade.value || !selectedSemester.value) {
        ElMessage.warning("年级和学期为必选项");
        return;
      }

      loading.value = true;  // 开始加载
      try {
        const params = {
          semester_id: selectedSemester.value,
        };

        if (!selectedClass.value) {
          params.college_id = selectedCollege.value;
        } else {
          params.class_id = selectedClass.value;
          params.college_id = selectedCollege.value;
        }

        const response = await axios.get("/api/v1/order/list", { params });

        if (response.data.code === 200) {
          ElMessage.success("查询成功");
          bookTableData.value = [];

          const orders = response.data.data.filter(order => order.grade === selectedGrade.value);
          tag.value = orders.length > 0 ? 1 : 0;

          console.log(orders); // 打印过滤后的订单数据

          const bookQuantityMap = {};
          for (const order of orders) {
            const orderId = order.id;
            const detailResponse = await axios.get(`/api/v1/order/details/?id=${orderId}`);
            if (detailResponse.data.code === 200 && detailResponse.data.data && detailResponse.data.data.length > 0) {
              for (const orderDetail of detailResponse.data.data) {
                const learningMaterialId = orderDetail.learning_material_id;
                const materialResponse = await axios.get(`/api/v1/learning_material/info/?id=${learningMaterialId}`);
                if (materialResponse.data.code === 200) {
                  const bookInfo = {
                    name: materialResponse.data.data.name,
                    author: materialResponse.data.data.author,
                    description: materialResponse.data.data.description,
                    category: materialResponse.data.data.category,
                  };
                  const bookKey = `${bookInfo.name}-${bookInfo.author}`;
                  if (bookQuantityMap[bookKey]) {
                    bookQuantityMap[bookKey].quantity += orderDetail.quantity;
                  } else {
                    bookQuantityMap[bookKey] = {
                      ...bookInfo,
                      quantity: orderDetail.quantity,
                      unitPrice: orderDetail.unit_price,
                    };
                  }
                } else {
                  ElMessage.error(materialResponse.data.msg || "获取书本信息失败");
                }
              }
            }
          }
          for (const bookKey in bookQuantityMap) {
            bookTableData.value.push(bookQuantityMap[bookKey]);
          }
        } else {
          ElMessage.error(response.data.msg || "查询失败");
        }
      } catch (error) {
        ElMessage.error("网络错误，无法查询订单");
      } finally {
        loading.value = false;  // 完成加载
      }
    };

    const sortClasses = () => {
      classes.value.sort(((a, b) => {
        const extractNumber = (str) => {
          const match = str.match(/(\d+)/);
          return match ? parseInt(match, 10) : Number(str);
        };
        const numA = extractNumber(a.name);
        const numB = extractNumber(b.name);
        const textA = a.name.replace(/\d+/g, '');
        const textB = b.name.replace(/\d+/g, '');
        if (textA.localeCompare(textB) !== 0) {
          return textA.localeCompare(textB);
        }
        return numA - numB;
      }));
    };

//     const exportToExcel = () => {
//   if (bookTableData.value.length === 0) {
//     ElMessage.warning("没有数据可以导出");
//     return;
//   }
//   const formattedData = bookTableData.value.map(item => ({
//     '书名': item.name,
//     '作者': item.author,
//     '描述': item.description,
//     '类别': item.category,
//     '数量': item.quantity,
//     '单价': item.unitPrice,
//   }));
//   // 定义表头为中文名称
//   const headers = ['书名', '作者', '描述', '类别', '单价', '数量'];
//   const worksheet = XLSX.utils.json_to_sheet(formattedData, { header: headers });
//   const workbook = XLSX.utils.book_new();
//   XLSX.utils.book_append_sheet(workbook, worksheet, "订单统计");

//   // 动态生成文件名，包含所选年级和班级的名称
//   const className = getClassNameById(selectedClass.value); 
//   const fileName = `订单统计-${selectedGrade.value}-${className}.xlsx`;
//   XLSX.writeFile(workbook, fileName);
// };

// const getClassNameById = (id) => {
//   const classItem = classes.value.find(classItem => classItem.id === id);
//   return classItem ? classItem.name : '未知班级';
// };

const exportToExcel = async () => {
  if (!selectedClass.value || !selectedSemester.value) {
    ElMessage.warning("请选择班级和学期");
    return;
  }

  const params = new URLSearchParams({
    class_id: selectedClass.value,
    semester_id: selectedSemester.value
  });

  try {
    const response = await axios({
      method: 'GET',
      url: '/api/v1/order/export_class_orders',
      params,
      responseType: 'blob', // 重要：设置响应类型为blob
    });

    if (response.status === 200) {
      // 创建一个链接元素用于下载
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `订单统计-${selectedGrade.value}-${getClassNameById(selectedClass.value)}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); // 下载后移除元素
    } else {
      ElMessage.error("导出失败");
    }
  } catch (error) {
    ElMessage.error("网络错误，无法导出订单");
  }
};

const getClassNameById = (id) => {
  const classItem = classes.value.find(classItem => classItem.id === id);
  return classItem ? classItem.name : '未知班级';
};

    onMounted(() => {
      fetchCollegesData();
      fetchSemestersData();
    });

    watch(
      [selectedCollege, selectedGrade, selectedClass],
      () => {
        fetchClassesData();
      },
      { immediate: false }
    );

    return {
      colleges,
      classes,
      semesters,
      selectedCollege,
      selectedGrade,
      selectedSemester,
      selectedClass,
      years,
      bookTableData,
      loading,
      fetchOrders,
      onCollegeChange,
      sortClasses,
      tag,
      exportToExcel,
    };
  },
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  flex: 1;
  text-align: center;
  margin: 0;
}

.query-button {
  margin-left: 20px;
}

.table-container {
  margin-top: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
}

tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.8);
  z-index: 999;
}

.loading-spinner {
  font-size: 24px;
  color: #409eff;
}

.loading-text {
  margin-top: 10px;
  font-size: 16px;
  color: #333;
}

</style>
